package com.walkline.screen;

import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.Vector;

import javax.microedition.io.HttpConnection;

import net.rim.device.api.i18n.DateFormat;
import net.rim.device.api.i18n.SimpleDateFormat;
import net.rim.device.api.io.IOUtilities;
import net.rim.device.api.io.http.HttpProtocolConstants;
import net.rim.device.api.io.transport.ConnectionDescriptor;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Characters;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.FontFamily;
import net.rim.device.api.ui.FontManager;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.Ui;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.Menu;
import net.rim.device.api.ui.component.pane.HorizontalScrollableController;
import net.rim.device.api.ui.component.pane.HorizontalScrollableTitleView;
import net.rim.device.api.ui.component.pane.Pane;
import net.rim.device.api.ui.component.pane.PaneManagerController;
import net.rim.device.api.ui.component.pane.PaneManagerModel;
import net.rim.device.api.ui.component.pane.PaneManagerView;
import net.rim.device.api.ui.component.pane.PaneView;
import net.rim.device.api.ui.component.pane.TitleView;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.menu.SubMenu;
import net.rim.device.api.ui.picker.DateTimePicker;
import net.rim.device.api.util.StringProvider;

import com.walkline.app.ZhihuAppConfig;
import com.walkline.util.Enumerations.RefreshActions;
import com.walkline.util.Function;
import com.walkline.util.network.MyConnectionFactory;
import com.walkline.util.network.WorkQueue;
import com.walkline.util.ui.ForegroundManager;
import com.walkline.util.ui.ListStyleButtonField;
import com.walkline.util.ui.ListStyleButtonSet;
import com.walkline.zhihu.ZhihuSDK;
import com.walkline.zhihu.inf.DailyStories;
import com.walkline.zhihu.inf.HotStories;
import com.walkline.zhihu.inf.HotStory;
import com.walkline.zhihu.inf.Section;
import com.walkline.zhihu.inf.Sections;
import com.walkline.zhihu.inf.Story;

public class ZhihuScreen extends MainScreen
{
	private ZhihuSDK _zhihu = ZhihuSDK.getInstance();
	private WorkQueue _queue = new WorkQueue(3);

	private PaneManagerView _paneManagerView;
	private ForegroundManager _foregroundDaily;
	private ForegroundManager _foregroundHot;
	private ForegroundManager _foregroundSections;
	private ListStyleButtonField _item;
	private ListStyleButtonSet _dailyStoriesSet = new ListStyleButtonSet();
	private ListStyleButtonSet _hotStoriesSet = new ListStyleButtonSet();
	private ListStyleButtonSet _sectionsSet = new ListStyleButtonSet();

	private Calendar _currentDate = Calendar.getInstance();
	private SimpleDateFormat STORY_DATEFORMAT = ZhihuAppConfig.STORY_DATEFORMAT;
	private LabelField _labelTitle = new LabelField(ZhihuAppConfig.APP_TITLE);

    public ZhihuScreen()
    {
        super (NO_VERTICAL_SCROLL | USE_ALL_HEIGHT | NO_SYSTEM_MENU_ITEMS);

		try {
			FontFamily family = FontFamily.forName("BBGlobal Sans");
			Font appFont = family.getFont(Font.PLAIN, 8, Ui.UNITS_pt);
			FontManager.getInstance().setApplicationFont(appFont);
		} catch (ClassNotFoundException e) {}

        setTitle(_labelTitle);
        setDefaultClose(false);

		LabelField paneTitle1 = new LabelField("新闻浏览") {protected void paint(Graphics g) {g.setColor(Color.WHITE); super.paint(g);}};
		LabelField paneTitle2 = new LabelField("热门新闻") {protected void paint(Graphics g) {g.setColor(Color.WHITE); super.paint(g);}};
		LabelField paneTitle3 = new LabelField("专题分类") {protected void paint(Graphics g) {g.setColor(Color.WHITE); super.paint(g);}};

		//paneTitle1.setFont(ZhihuAppConfig.FONT_PANEVIEW_TITLE);
		//paneTitle2.setFont(ZhihuAppConfig.FONT_PANEVIEW_TITLE);
		//paneTitle3.setFont(ZhihuAppConfig.FONT_PANEVIEW_TITLE);
		//paneTitle4.setFont(ZhihuAppConfig.FONT_PANEVIEW_TITLE);

		Pane pane1 = new Pane(paneTitle1, createDailyUi());
		Pane pane2 = new Pane(paneTitle2, createHotUi());
		Pane pane3 = new Pane(paneTitle3, createSectionsUi());

		PaneManagerModel model = new PaneManagerModel();
		model.addPane(pane1);
		model.addPane(pane2);
		model.addPane(pane3);
		model.setCurrentlySelectedIndex(0);
        model.enableLooping(true);

    	TitleView titleView = new HorizontalScrollableTitleView(FOCUSABLE);
    	titleView.setModel(model);

        PaneView paneView = new PaneView(Field.FOCUSABLE);
        paneView.setModel(model);

        _paneManagerView = new PaneManagerView(Field.FOCUSABLE, titleView, paneView);
        _paneManagerView.setModel(model);
        model.setView(_paneManagerView);

        PaneManagerController controller = new HorizontalScrollableController();
        controller.setModel(model);
        controller.setView(_paneManagerView);
        model.setController(controller);
        _paneManagerView.setController(controller);

        add(_paneManagerView);

        UiApplication.getUiApplication().invokeLater(new Runnable()
        {
			public void run() {getLatestStories(true);}// getHotStories(true); getSections(false);}
		});
    }

    private ForegroundManager createDailyUi()
    {
    	_foregroundDaily = new ForegroundManager(NON_FOCUSABLE) {
    		protected boolean navigationMovement(int dx, int dy, int status, int time)
    	    {
    			if (_dailyStoriesSet.getManager() != null) {_dailyStoriesSet.setFocus();}

    			if (_paneManagerView.isAnimating()) {return true;}

    			if (dx<0)
    			{
    				setTitle(ZhihuAppConfig.APP_TITLE);
    				doAnimatingPanes(2, PaneManagerView.DIRECTION_BACKWARDS);

					if (_sectionsSet.getManager() != null)
					{
						_sectionsSet.setFocus();
					} else {
						getSections(true);
					}

    				return true;
    			} 

    			if (dx>0)
    			{
    				setTitle(ZhihuAppConfig.APP_TITLE);
    				doAnimatingPanes(1, PaneManagerView.DIRECTION_FORWARDS);

					if (_hotStoriesSet.getManager() != null)
					{
						_hotStoriesSet.setFocus();
					} else {
						getHotStories(true);
					}

    				return true;
    			}
    			
    			return super.navigationMovement(dx, dy, status, time);
    	    }
    	};

    	return _foregroundDaily;
    }

    private ForegroundManager createHotUi()
    {
    	_foregroundHot = new ForegroundManager(NON_FOCUSABLE) {
    		protected boolean navigationMovement(int dx, int dy, int status, int time)
    	    {
    			if (_hotStoriesSet.getManager() != null) {_hotStoriesSet.setFocus();}

    			if (_paneManagerView.isAnimating()) {return true;}

    			if (dx<0)
    			{
					setTitle(ZhihuAppConfig.APP_TITLE + " - " + STORY_DATEFORMAT.formatLocal(_currentDate.getTime().getTime() - ZhihuAppConfig.ONE_DAY));							
    				doAnimatingPanes(0, PaneManagerView.DIRECTION_BACKWARDS);

					if (_dailyStoriesSet.getManager() != null)
					{
						_dailyStoriesSet.setFocus();
					} else {
						getLatestStories(true);
					}

    				return true;
    			} 

    			if (dx>0)
    			{
    				setTitle(ZhihuAppConfig.APP_TITLE);
    				doAnimatingPanes(2, PaneManagerView.DIRECTION_FORWARDS);

					if (_sectionsSet.getManager() != null)
					{
						_sectionsSet.setFocus();
					} else {
						getSections(true);
					}

    				return true;
    			}

    			return super.navigationMovement(dx, dy, status, time);
    	    }
    	};

    	return _foregroundHot;
    }

    private ForegroundManager createSectionsUi()
    {
    	_foregroundSections = new ForegroundManager(NON_FOCUSABLE) {
    		protected boolean navigationMovement(int dx, int dy, int status, int time)
    	    {
    			if (_sectionsSet.getManager() != null) {_sectionsSet.getFocus();}

    			if (_paneManagerView.isAnimating()) {return true;}

    			if (dx<0)
    			{
    				setTitle(ZhihuAppConfig.APP_TITLE);
    				doAnimatingPanes(1, PaneManagerView.DIRECTION_BACKWARDS);

					if (_hotStoriesSet.getManager() != null)
					{
						_hotStoriesSet.setFocus();
					} else {
						getHotStories(true);
					}

    				return true;
    			} 

    			if (dx>0)
    			{
					setTitle(ZhihuAppConfig.APP_TITLE + " - " + STORY_DATEFORMAT.formatLocal(_currentDate.getTime().getTime() - ZhihuAppConfig.ONE_DAY));							
    				doAnimatingPanes(0, PaneManagerView.DIRECTION_FORWARDS);

					if (_dailyStoriesSet.getManager() != null)
					{
						_dailyStoriesSet.setFocus();
					} else {
						getLatestStories(true);
					}

    				return true;
    			}

    			return super.navigationMovement(dx, dy, status, time);
    	    }
    	};

    	return _foregroundSections;
    }

	private void doAnimatingPanes(final int currentPane, final int direction)
    {
		UiApplication.getApplication().invokeAndWait(new Runnable()
		{
			public void run()
			{
				_paneManagerView.jumpTo(currentPane, direction);
				_paneManagerView.getModel().setCurrentlySelectedIndex(currentPane, true);
			}
		});
    }

    private void getStories(final String date, final boolean active)
    {
    	if (active)
    	{
    		int currentPane = _paneManagerView.getModel().currentlySelectedIndex();
    		int direction = PaneManagerView.DIRECTION_NONE;

    		if (currentPane == 1) {direction = PaneManagerView.DIRECTION_BACKWARDS;}
    		if (currentPane == 2) {direction = PaneManagerView.DIRECTION_FORWARDS;}

    		doAnimatingPanes(0, direction);
    		//if (_dailyStoriesSet.getManager() != null) {_dailyStoriesSet.setFocus();}
    	}

    	UiApplication.getUiApplication().invokeLater(new Runnable()
    	{
			public void run()
			{
		    	DailyStories dailyStories;
				RefreshStoriesScreen popupScreen = new RefreshStoriesScreen(_zhihu, date, RefreshActions.DAILYSTORIES);
				UiApplication.getUiApplication().pushModalScreen(popupScreen);

				dailyStories = popupScreen.getDailyStories();

				if (popupScreen != null) {popupScreen = null;}
				if (dailyStories != null)
				{
					refreshDailyStories(dailyStories);
					if (active)
					{
						_dailyStoriesSet.setFocus();
						setTitle(ZhihuAppConfig.APP_TITLE + " - " + dailyStories.getDate());
					}
				}
			}
		});
    }

    private void getHotStories(final boolean active)
    {
    	if (active)
    	{
    		int currentPane = _paneManagerView.getModel().currentlySelectedIndex();
    		int direction = PaneManagerView.DIRECTION_NONE;

    		if (currentPane == 0) {direction = PaneManagerView.DIRECTION_FORWARDS;}
    		if (currentPane == 2) {direction = PaneManagerView.DIRECTION_BACKWARDS;}

        	doAnimatingPanes(1, direction);
    	}

    	UiApplication.getUiApplication().invokeLater(new Runnable()
    	{
			public void run()
			{
		    	HotStories hotStories;
				RefreshStoriesScreen popupScreen = new RefreshStoriesScreen(_zhihu, null, RefreshActions.HOTSTORIES);
				UiApplication.getUiApplication().pushModalScreen(popupScreen);

				hotStories = popupScreen.getHotStories();

				if (popupScreen != null) {popupScreen = null;}
				if (hotStories != null)
				{
					refreshHotStories(hotStories);
					if (active)
					{
						_hotStoriesSet.setFocus();
						setTitle(ZhihuAppConfig.APP_TITLE);
					}
				}
			}
		});
    }

    private void getSections(final boolean active)
    {
    	if (active)
    	{
    		int currentPane = _paneManagerView.getModel().currentlySelectedIndex();
    		int direction = PaneManagerView.DIRECTION_NONE;

    		if (currentPane == 0) {direction = PaneManagerView.DIRECTION_BACKWARDS;}
    		if (currentPane == 1) {direction = PaneManagerView.DIRECTION_FORWARDS;}

        	doAnimatingPanes(2, direction);
    	}

    	UiApplication.getUiApplication().invokeLater(new Runnable()
    	{
			public void run()
			{
		    	Sections sections;
		    	RefreshStoriesScreen popupScreen = new RefreshStoriesScreen(_zhihu, null, RefreshActions.SECTIONS);
		    	UiApplication.getUiApplication().pushModalScreen(popupScreen);

		    	sections = popupScreen.getSections();

		    	if (popupScreen != null) {popupScreen = null;}
		    	if (sections != null)
		    	{
		    		refreshSections(sections);
		    		if (active)
		    		{
		    			_sectionsSet.setFocus();
		    			setTitle(ZhihuAppConfig.APP_TITLE);
		    		}
		    	}
			}
		});
    }

    private void refreshDailyStories(DailyStories dailyStories)
    {
    	if (_dailyStoriesSet.getManager() == null) {_foregroundDaily.add(_dailyStoriesSet);}
		if (_dailyStoriesSet.getFieldCount() > 0) {_dailyStoriesSet.deleteAll();}

		Vector storiesVector = dailyStories.getStories();
		Story story;

		for (int i=0; i<storiesVector.size(); i++)
		{
			story = (Story) storiesVector.elementAt(i);
			if (story != null)
			{
				_item = new ListStyleButtonField(story);
				_item.setChangeListener(new FieldChangeListener()
				{
					public void fieldChanged(Field field, int context)
					{
						if (context != FieldChangeListener.PROGRAMMATIC) {showStoryDetailScreen();}
					}
				});

				_dailyStoriesSet.add(_item);
			}
		}

		if (_dailyStoriesSet.getFieldCount() > 0)
		{
			UiApplication.getUiApplication().invokeLater(new Runnable()
			{
				public void run() {refreshDailyListIcons();}
			});
		}
    }

    private void refreshHotStories(HotStories hotStories)
    {
    	if (_hotStoriesSet.getManager() == null) {_foregroundHot.add(_hotStoriesSet);}
		if (_hotStoriesSet.getFieldCount() > 0) {_hotStoriesSet.deleteAll();}

		Vector storiesVector = hotStories.getHotStories();
		HotStory story;

		for (int i=0; i<storiesVector.size(); i++)
		{
			story = (HotStory) storiesVector.elementAt(i);
			if (story != null)
			{
				_item = new ListStyleButtonField(story);
				_item.setChangeListener(new FieldChangeListener()
				{
					public void fieldChanged(Field field, int context)
					{
						if (context != FieldChangeListener.PROGRAMMATIC) {showHotStoryDetailScreen();}
					}
				});

				_hotStoriesSet.add(_item);
			}
		}

		if (_hotStoriesSet.getFieldCount() > 0)
		{
			UiApplication.getUiApplication().invokeLater(new Runnable()
			{
				public void run() {refreshHotListIcons();}
			});
		}
    }

    private void refreshSections(Sections sections)
    {
    	if (_sectionsSet.getManager() == null) {_foregroundSections.add(_sectionsSet);}
		if (_sectionsSet.getFieldCount() > 0) {_sectionsSet.deleteAll();}

		Vector storiesVector = sections.getSections();
		Section section;

		for (int i=0; i<storiesVector.size(); i++)
		{
			section = (Section) storiesVector.elementAt(i);
			if (section != null)
			{
				_item = new ListStyleButtonField(section);
				_item.setChangeListener(new FieldChangeListener()
				{
					public void fieldChanged(Field field, int context)
					{
						if (context != FieldChangeListener.PROGRAMMATIC) {showSectionsScreen();}
					}
				});

				_sectionsSet.add(_item);
			}
		}

		if (_sectionsSet.getFieldCount() > 0)
		{
			UiApplication.getUiApplication().invokeLater(new Runnable()
			{
				public void run() {refreshSectionListIcons();}
			});
		}
    }

    private void refreshDailyListIcons()
    {
		ListStyleButtonField item;

		_queue.removeAll();

		for (int i=0; i<_dailyStoriesSet.getFieldCount(); i++)
		{
			Field object = _dailyStoriesSet.getField(i);

			if (object instanceof ListStyleButtonField)
			{
				item = (ListStyleButtonField) object;
				_queue.execute(new DownloadImages(item));
			}
		}
    }

    private void refreshHotListIcons()
    {
		ListStyleButtonField item;

		//_queue.removeAll();

		for (int i=0; i<_hotStoriesSet.getFieldCount(); i++)
		{
			Field object = _hotStoriesSet.getField(i);

			if (object instanceof ListStyleButtonField)
			{
				item = (ListStyleButtonField) object;
				_queue.execute(new DownloadImages(item));
			}
		}
    }

    private void refreshSectionListIcons()
    {
		ListStyleButtonField item;

		//_queue.removeAll();

		for (int i=0; i<_sectionsSet.getFieldCount(); i++)
		{
			Field object = _sectionsSet.getField(i);

			if (object instanceof ListStyleButtonField)
			{
				item = (ListStyleButtonField) object;
				_queue.execute(new DownloadImages(item));
			}
		}
    }

    class DownloadImages implements Runnable
    {
    	ListStyleButtonField _item;
		//MyConnectionFactory cf = new MyConnectionFactory();
    	MyConnectionFactory _factory = new MyConnectionFactory();
    	HttpConnection _conn = null;
    	InputStream inputStream = null;

    	public DownloadImages(ListStyleButtonField item) {_item = item;}

		public void run()
		{
			if (_item.getThumbnailUrl().equalsIgnoreCase("")) {return;}

			ConnectionDescriptor connd = _factory.getConnection(_item.getThumbnailUrl());

			if (connd == null) {return;}

			try {
				_conn = (HttpConnection) connd.getConnection();
				_conn.setRequestProperty(HttpProtocolConstants.HEADER_CONNECTION, HttpProtocolConstants.HEADER_KEEP_ALIVE);

				inputStream = _conn.openInputStream();

				if (inputStream.available() > 0)
				{
					byte[] data = IOUtilities.streamToBytes(inputStream);

					if (data.length == _conn.getLength()) {_item.setThumbnail(data);}
				}

				inputStream.close();
				//_conn.close();
			} catch (IOException e) {}
		}
	}

    private void showStoryDetailScreen()
    {
    	ListStyleButtonField item = (ListStyleButtonField) _dailyStoriesSet.getFieldWithFocus();

    	UiApplication.getUiApplication().pushScreen(new StoryDetailsScreen(_zhihu, item.getUrl(), RefreshActions.STORYDETAILS));
    }

    private void showHotStoryDetailScreen()
    {
    	ListStyleButtonField item = (ListStyleButtonField) _hotStoriesSet.getFieldWithFocus();

    	UiApplication.getUiApplication().pushScreen(new StoryDetailsScreen(_zhihu, item.getUrl(), RefreshActions.STORYDETAILS));
    }

    private void showSectionsScreen()
    {
    	ListStyleButtonField item = (ListStyleButtonField) _sectionsSet.getFieldWithFocus();

    	UiApplication.getUiApplication().pushScreen(new SectionDetailsScreen(_zhihu, item.getSectionName(), item.getSectionId()));
    }

    private void getBeforeStories()
    {
    	Calendar calendar = Calendar.getInstance();
    	calendar.setTime(new Date(calendar.getTime().getTime() - ZhihuAppConfig.ONE_DAY));

    	DateTimePicker dtPicker = DateTimePicker.createInstance(calendar, "yyyy-MM-dd", null);
    	dtPicker.setMaximumDate(calendar);

    	calendar.set(Calendar.YEAR, 2013);
    	calendar.set(Calendar.MONTH, 5 - 1);
    	calendar.set(Calendar.DAY_OF_MONTH, 19);
    	dtPicker.setMinimumDate(calendar);

    	if (dtPicker.doModal(DateFormat.DATE_FIELD))
    	{
    		_currentDate = dtPicker.getDateTime();
    		_currentDate.set(Calendar.DAY_OF_MONTH, _currentDate.get(Calendar.DAY_OF_MONTH) + 1);

    		getStories(STORY_DATEFORMAT.formatLocal(dtPicker.getDateTime().getTime().getTime() + ZhihuAppConfig.ONE_DAY), true);	
    	}
    }

    private void getLatestStories(boolean active)
    {
    	_currentDate = Calendar.getInstance();
		_currentDate.set(Calendar.DAY_OF_MONTH, _currentDate.get(Calendar.DAY_OF_MONTH) + 1);
		getStories(null, active);
    }

    /*
    private void refreshStories()
    {
    	if (STORY_DATEFORMAT.formatLocal(Calendar.getInstance().getTime().getTime()).equalsIgnoreCase(STORY_DATEFORMAT.formatLocal(_currentDate.getTime().getTime() - ZhihuAppConfig.ONE_DAY)))
    	{
    		getStories(null);
    	} else {
    		getStories(STORY_DATEFORMAT.formatLocal(_currentDate.getTime().getTime()));
    	}
    }
    */

    private void getNextStories()
    {
    	_currentDate.set(Calendar.DAY_OF_MONTH, _currentDate.get(Calendar.DAY_OF_MONTH) + 1);

    	if (STORY_DATEFORMAT.formatLocal(_currentDate.getTime().getTime()).equalsIgnoreCase(STORY_DATEFORMAT.formatLocal(Calendar.getInstance().getTime().getTime() + ZhihuAppConfig.ONE_DAY * 2)))
    	{
    		Function.errorDialog("这是最新的内容，不要再向后翻了！");
    		_currentDate.set(Calendar.DAY_OF_MONTH, _currentDate.get(Calendar.DAY_OF_MONTH) - 1);
    	} else if (STORY_DATEFORMAT.formatLocal(_currentDate.getTime().getTime()).equalsIgnoreCase(STORY_DATEFORMAT.formatLocal(Calendar.getInstance().getTime().getTime() + ZhihuAppConfig.ONE_DAY))) {
    		getLatestStories(true);
    	} else {
    		getStories(STORY_DATEFORMAT.formatLocal(_currentDate.getTime().getTime()), true);
    	}
    }

    private void getPrevStories()
    {
    	_currentDate.set(Calendar.DAY_OF_MONTH, _currentDate.get(Calendar.DAY_OF_MONTH) - 1);

    	if (STORY_DATEFORMAT.formatLocal(_currentDate.getTime().getTime()).equalsIgnoreCase("20130519"))
    	{
    		Function.errorDialog("这是第一期的内容，不要再向前翻了！");
    		_currentDate.set(Calendar.DAY_OF_MONTH, _currentDate.get(Calendar.DAY_OF_MONTH) + 1);
    	} else {
    		getStories(STORY_DATEFORMAT.formatLocal(_currentDate.getTime().getTime()), true);
    	}
    }

    private void showExitDialog()
    {
		String[] yesno = {"是 (Y\u0332)", "否 (N\u0332)"};
		Dialog showDialog = new Dialog("确认退出知乎日报？", yesno, null, 0, Bitmap.getPredefinedBitmap(Bitmap.QUESTION), USE_ALL_WIDTH);

		showDialog.doModal();
		if (showDialog.getSelectedValue() == 0) {System.exit(0);}
    }

    private void showAboutScreen()
    {
    	UiApplication.getUiApplication().pushScreen(new AboutScreen());
    }

    protected boolean keyChar(char key, int status, int time)
    {
    	int currentPage = _paneManagerView.getModel().currentlySelectedIndex();

    	switch (key)
    	{
    		/*
    		case Characters.SPACE:
    			switch (currentPage)
    			{
					case 0:
						if (_dailyStoriesSet.getFieldCount() > 0)
						{
							int count = _dailyStoriesSet.getFieldWithFocusIndex();

							if (count < _dailyStoriesSet.getFieldCount()) {_dailyStoriesSet.getField(count + 1).setFocus();}
						}
						break;
					case 1:
						break;
					case 2:
						break;
				}
    			return true;
    		*/
			case Characters.LATIN_CAPITAL_LETTER_R:
			case Characters.LATIN_SMALL_LETTER_R:
				//refreshStories();
				return true;
			case Characters.LATIN_CAPITAL_LETTER_L:
			case Characters.LATIN_SMALL_LETTER_L:
				getLatestStories(true);
				return true;
			case Characters.LATIN_CAPITAL_LETTER_T:
			case Characters.LATIN_SMALL_LETTER_T:
				switch (currentPage)
				{
					case 0:
						if (_dailyStoriesSet.getFieldCount() > 0) {_dailyStoriesSet.getField(0).setFocus();}
						break;
					case 1:
						if (_hotStoriesSet.getFieldCount() > 0) {_hotStoriesSet.getField(0).setFocus();}
						break;
					case 2:
						if (_sectionsSet.getFieldCount() > 0) {_sectionsSet.getField(0).setFocus();}
						break;
				}
				//if (_dailyStoriesSet.getFieldCount() > 0) {_dailyStoriesSet.getField(0).setFocus();}
				return true;
			case Characters.LATIN_CAPITAL_LETTER_B:
			case Characters.LATIN_SMALL_LETTER_B:
				switch (currentPage)
				{
					case 0:
						if (_dailyStoriesSet.getFieldCount() > 0) {_dailyStoriesSet.getField(_dailyStoriesSet.getFieldCount()-1).setFocus();}
						break;
					case 1:
						if (_hotStoriesSet.getFieldCount() > 0) {_hotStoriesSet.getField(_hotStoriesSet.getFieldCount()-1).setFocus();}
						break;
					case 2:
						if (_sectionsSet.getFieldCount() > 0) {_sectionsSet.getField(_sectionsSet.getFieldCount()-1).setFocus();}
						break;
				}
				//if (_dailyStoriesSet.getFieldCount() > 0) {_dailyStoriesSet.getField(_dailyStoriesSet.getFieldCount()-1).setFocus();}
				return true;
			case Characters.LATIN_CAPITAL_LETTER_N:
			case Characters.LATIN_SMALL_LETTER_N:
				getNextStories();
				return true;
			case Characters.LATIN_CAPITAL_LETTER_P:
			case Characters.LATIN_SMALL_LETTER_P:
				getPrevStories();
				return true;
			case Characters.LATIN_CAPITAL_LETTER_A:
			case Characters.LATIN_SMALL_LETTER_A:
				showAboutScreen();
				return true;
			case Characters.LATIN_CAPITAL_LETTER_C:
			case Characters.LATIN_SMALL_LETTER_C:
				getBeforeStories();
				return true;
			case Characters.LATIN_CAPITAL_LETTER_H:
			case Characters.LATIN_SMALL_LETTER_H:
				getHotStories(true);
				return true;
			case Characters.LATIN_CAPITAL_LETTER_S:
			case Characters.LATIN_SMALL_LETTER_S:
				getSections(true);
				return true;
			case Characters.LATIN_CAPITAL_LETTER_Q:
			case Characters.LATIN_SMALL_LETTER_Q:
				showExitDialog();
				return true;
		}

    	return super.keyChar(key, status, time);
    }

    MenuItem menuRefresh = new MenuItem(new StringProvider("刷新(R\u0332)"), 100, 10)
    {
    	public void run() {}//refreshStories();}
    };

    MenuItem menuLatestStories = new MenuItem(new StringProvider("今日新闻(L\u0332)"), 100, 20)
    {
    	public void run() {getLatestStories(true);}
    };

    MenuItem menuHotStories = new MenuItem(new StringProvider("热门新闻(H\u0332)"), 100, 30)
    {
    	public void run() {getHotStories(true);}
    };

    MenuItem menuSections = new MenuItem(new StringProvider("专题分类(S\u0332)"), 100, 30)
    {
    	public void run() {getSections(true);}
    };

    MenuItem menuBeforeStoriesSelector = new MenuItem(new StringProvider("指定日期(C\u0332)"), 200, 10)
    {
    	public void run() {getBeforeStories();}
    };

    MenuItem menuBeforeStoriesPrev = new MenuItem(new StringProvider("上一期(P\u0332)"), 200, 20)
    {
    	public void run() {getPrevStories();}
    };

    MenuItem menuBeforeStoriesNext = new MenuItem(new StringProvider("下一期(N\u0332)"), 200, 30)
    {
    	public void run() {getNextStories();}
    };

    MenuItem menuAbout = new MenuItem(new StringProvider("关于(A\u0332)"), 100, 60)
    {
    	public void run() {showAboutScreen();}
    };

    MenuItem menuQuit = new MenuItem(new StringProvider("退出(Q\u0332)"), 100, 70)
    {
    	public void run() {showExitDialog();}
    };

    protected void makeMenu(Menu menu, int instance)
    {
    	SubMenu menuBeforeStories = new SubMenu(null, "往期新闻", 100, 50);
    	menuBeforeStories.add(menuBeforeStoriesSelector);
    	menuBeforeStories.addSeparator();
    	menuBeforeStories.add(menuBeforeStoriesPrev);
    	menuBeforeStories.add(menuBeforeStoriesNext);

    	//menu.add(menuRefresh);
    	//menu.addSeparator();
    	menu.add(menuLatestStories);
    	menu.add(menuHotStories);
    	menu.add(menuSections);
    	menu.addSeparator();
    	menu.add(menuBeforeStories);
    	menu.addSeparator();
    	menu.add(menuAbout);
    	menu.addSeparator();
    	menu.add(menuQuit);

    	super.makeMenu(menu, instance);
    };

    protected boolean onSavePrompt() {return true;}

    public boolean onClose()
    {
    	UiApplication.getUiApplication().requestBackground();

    	return true;
    }
}